import {
  addArticle
} from '../../api/index'
import {
  articleType,
  showType
} from '../../utils/type';

const app = getApp()
Page({
  data: {
    logined: true,
    baseCls: 'page_account',
    showType,
    articleType,
    ArticleForm: {
      title: '',
      content: '',
      type: '0',
      status: '1',
      urlItems: []
    }
  },
  onShow: function () {
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        logined: true,
        userInfo: userInfo
      })
    } else {
      this.goHome()
    }
  },

  //获取标题
  getTitle(e) {
    this.setData({
      'ArticleForm.title': e.detail
    })
  },
  // 获取内容
  getContent(e) {
    this.setData({
      'ArticleForm.content': e.detail
    })
  },
  // 获取图片 
  getVal(e) {
    const urls = e.detail.val.map(item => {
      return item.url
    })
    this.setData({
      'ArticleForm.urlItems': urls
    })
  },
  /* 内容状态 */
  getState(e) {
    this.setData({
      'ArticleForm.status': e.detail.value.value
    })
  },
  /* 内容类型 */
  getType(e) {
    this.setData({
      'ArticleForm.type': e.detail.value.value
    })
  },
  /**
   * 新建图文 
   */
  addArticle() {
    let that = this;
    let fields = that.data.ArticleForm;

    if (
      typeof (fields.title) !== 'undefined' && 
      typeof (fields.content) !== 'undefined' &&
      typeof (fields.status) !== 'undefined' && 
      typeof (fields.type) !== 'undefined' &&
      typeof (fields.urlItems) !== 'undefined'
    ) {
      addArticle(fields).then(res => {
        wx.showToast({
          title: '新增成功',
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 1000)
      })
    } else {
      that.setData({
        disabled: false
      })
      wx.showToast({
        title: '请完整填写表单',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 跳转首页
   */
  goHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
})